package com.example.mqttledmenu;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

class HttpUtil {
    public void sendOKHttpRequest(String method, String address, Map<String, String> head, Map<String, String> body, Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request.Builder builder = new Request.Builder().url(address);
        if (head != null && head.size() > 0) {
            for (Map.Entry<String, String> entry : head.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        FormBody.Builder formBody = new FormBody.Builder();
        if (body != null && body.size() > 0) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                formBody.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = formBody.build();
        Request request = null;
        if (method.toUpperCase().equals("GET")) {
            //处理get请求
            request = builder.build();
        } else if (method.toUpperCase().equals("POST")) {
            //处理post请求
            request = builder.post(requestBody).build();
        } else {
            Log.e("nightowl", "请求方法确实");
        }
        client.newCall(request).enqueue(callback);
    }
    //请求示例
//    Map<String, String> body = new HashMap<String, String>();
//    body.put("userName",loginName);
//    body.put("password",password);
//    HttpUtil.sendOKHttpRequest(getString(R.string.ip)+"/xxx/Login",null,body,new Callback(){
//    public void onFailure(Call call,IOException e){}
//    public void onResponse(Call call,Response response)throws
//        IOException{final String responseText=response.body().string();//请求成功
// }});
    //图片处理函数
//    public static Bitmap getURLimage(String url) {
//        Bitmap bmp = null;
//        try {
//            URL targetUrl = new URL(url);// 获得连接
//            HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
//            conn.setConnectTimeout(6000);//设置超时
//            conn.setDoInput(true);
//            conn.setUseCaches(true);//不缓存
//            conn.connect();
//            InputStream is = conn.getInputStream();//获得图片的数据流
//            bmp = BitmapFactory.decodeStream(is);//读取图像数据
//            is.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return bmp;
//    }
}
